package com.redis;

import redis.clients.jedis.*;

import java.util.UUID;

/**
 * Created by buguniao on 16/4/4.
 */
public class RedisSemaphore {
    private String counter="counter";
    private String owner="owner";
    private String timeout="timeout";
    private int size=5;

    public RedisSemaphore(){

    }
    public RedisSemaphore(int size){
        this.size=size;
    }
    public String acquire(Jedis jedis){
        String clientId = UUID.randomUUID().toString();

        Long score = jedis.incr(counter);
        jedis.zadd(owner,score,clientId);
        jedis.zadd(timeout,System.currentTimeMillis(),clientId);
        Long rank = jedis.zrank(owner, clientId);

        if(rank<=size){
            return clientId;
        }else{
            return null;
        }
    }

    public void release(Jedis jedis,String clientId){
        jedis.zrem(owner,clientId);
        jedis.zrem(timeout,clientId);
    }

    public static void main(String[] args){
        JedisPool pool = new JedisPool("localhost",7000);

        Jedis jedis = pool.getResource();

        RedisSemaphore semaphore = new RedisSemaphore();
        String clientId = semaphore.acquire(jedis);
        System.out.println(clientId);
    }
}
